<template>
  <div class="dashboard-editor-container">
    <div style="display: flex; justify-content: space-between;">
      <Roundchart ref="round" class="echart-warpper"></Roundchart>
      <LineChart ref="line" class="echart-warpper"></LineChart>
    </div>
    <div style="display: flex;">
      <Memorychart ref="memory" class="echart-warpper"></Memorychart>
      <Cpuchart ref="cpu" class="echart-warpper"></Cpuchart>
      <Diskchart ref="disk" class="echart-warpper"></Diskchart>
    </div>
    <el-row :gutter="40" class="panel-group">
    <el-col
      :xs="12"
      :sm="12"
      :lg="6"
      class="card-panel-col"
      style="padding-left: 25px"
    >
      <div class="card-panel" @click="changeLine('task')">
        <div class="card-panel-description">
          <div class="card-panel-text">直播板卡1频道数</div>
          <count-to
            :start-val="0"
            :end-val="channleCount1"
            :duration="2600"
            class="card-panel-num"
          />
        </div>
      </div>
    </el-col>
    <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
      <div class="card-panel" @click="changeLine('task')">
        <div class="card-panel-description">
          <div class="card-panel-text">直播板卡2频道数</div>
          <count-to
            :start-val="0"
            :end-val="channleCount2"
            :duration="3000"
            class="card-panel-num"
          />
        </div>
      </div>
    </el-col>
    <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
      <div class="card-panel" @click="changeLine('task')">
        <div class="card-panel-description">
          <div class="card-panel-text">视频导入个数</div>
          <count-to
            :start-val="0"
            :end-val="contentCount"
            :duration="3000"
            class="card-panel-num"
          />
        </div>
      </div>
    </el-col>
    <!-- <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
      <div class="card-panel"  @click="changeLine('cert')">
        <div class="card-panel-description">
          <div class="card-panel-text">证书使用量 / 剩余量</div>
          <count-to
            :start-val="0"
            :end-val="certUseValue"
            :duration="3600"
            class="card-panel-num"
          />
          <font size="4">/</font>
          <count-to
            :start-val="0"
            :end-val="certIdleCount"
            :duration="3600"
            class="card-panel-num"
          />
        </div>
      </div>
    </el-col> -->

    <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
      <div class="card-panel" @click="changeLine('license')">
        <div class="card-panel-description">
          <div class="card-panel-text">今日导入视频个数</div>
          <count-to
            :start-val="0"
            :end-val="contentDayCount"
            :duration="3600"
            class="card-panel-num"
          />
        </div>
      </div>
    </el-col>
  </el-row>
  <!--    <el-row v-if="showTabFlag==='task'" >
      <el-tabs v-model="currentTab" class="center-tabs" v-show="showFlag === 'week'" @tab-click="handleTabClick">
      <el-tab-pane label="近一周" name="week" :lazy="true" />
      <el-tab-pane label="近一月" name="month" :lazy="true" />
    </el-tabs>
    <el-scrollbar class="right-scrollbar">
        <el-form v-if="currentTab==='week'"   style="background: #fff; padding: 16px 16px 0; margin-bottom: 32px;width: 100%;">
          <line-chart  :chart-data="lineChartData" />
        </el-form>
        <el-form v-if="currentTab === 'month'"  style="background: #fff; padding: 16px 16px 0; margin-bottom: 32px;width: 100%;">
          <line-chart  :chart-data="lineChartData" />
          </el-form>
        </el-scrollbar>
    </el-row>

   <el-row  v-if="showTabFlag==='cert'">
      <el-tabs v-model="currentTab" class="center-tabs" v-show="showFlag === 'week'" @tab-click="handleTabClick">
      <el-tab-pane label="近一周" name="week" :lazy="true" />
      <el-tab-pane label="近一月" name="month" :lazy="true" />
    </el-tabs>
    <el-scrollbar class="right-scrollbar">
        <el-form v-if="currentTab==='week'"   style="background: #fff; padding: 16px 16px 0; margin-bottom: 32px;width: 100%;">
          <line-chart  :chart-data="lineChartData" />
        </el-form>
        <el-form v-if="currentTab === 'month'"  style="background: #fff; padding: 16px 16px 0; margin-bottom: 32px;width: 100%;">
          <line-chart  :chart-data="lineChartData" />
          </el-form>
        </el-scrollbar>
    </el-row>


     <el-row v-if="showTabFlag==='license'">
      <el-tabs v-model="currentTab" class="center-tabs" v-show="showFlag === 'week'" @tab-click="handleTabClick">
      <el-tab-pane label="近一周" name="week" :lazy="true" />
      <el-tab-pane label="近一月" name="month" :lazy="true" />
    </el-tabs>
    <el-scrollbar class="right-scrollbar">
        <el-form v-if="currentTab==='week'"   style="background: #fff; padding: 16px 16px 0; margin-bottom: 32px;width: 100%;">
          <line-chart  :chart-data="lineChartData" />
        </el-form>
        <el-form v-if="currentTab === 'month'"  style="background: #fff; padding: 16px 16px 0; margin-bottom: 32px;width: 100%;">
          <line-chart  :chart-data="lineChartData" />
          </el-form>
        </el-scrollbar>
    </el-row> -->


  <!-- </div> -->


  <!-- <div class="app-container home"> -->
      <!-- 遮罩层和进度条 -->
      <div v-if="uploadProgress >= 0" class="upload-overlay" @click.prevent>
      <el-progress :percentage="uploadProgress"></el-progress>
    </div>

    <el-dialog :title="title" :visible.sync="openWarning" width="600px" append-to-body>
      <!-- <div slot="footer" > -->
       <div class="dialog-body">
        检测到当前服务器有挂载USB,可能存在文件需要导入,请问是否继续进行文件导入操作?
        <!-- 检测到有鉴权成功的移动硬盘插入请点击确认按钮进行内容卡拷贝- -->
       </div>
       <div slot="footer" >
          <el-button type="primary" @click="yes">立刻导入</el-button>
          <el-button @click="no">暂时不导入</el-button>
        </div>
      <!-- </div> -->
    </el-dialog>

     <el-dialog :title="title" :visible.sync="openDataScope" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件目录">
          <el-tree
      style="max-width: 600px"
      :data="treeData"
      :props="treeProps"
      :load="loadNode"
      lazy
      show-checkbox
      ref="tree"
    ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitData">确 定</el-button>
        <el-button @click="cancelData">取 消</el-button>
      </div>
    </el-dialog>


     <!-- 上传完成提示框 -->
     <el-dialog :title="uploadSuccessTitle" :visible.sync="uploadSuccessVisible" width="500px" append-to-body>
      <div>文件上传完成,请到内容管理模块查看上传的文件记录</div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeUploadSuccessDialog()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import CountTo from "vue-count-to";
import { checkUsb,getFileData,getFileDataByPath,getContentType,getContentTypeData } from '@/api/index';
import { getToken } from "@/utils/auth";
import axios from "axios";
import PanelGroup from "@/views/dashboard/PanelGroup";
import LineChart from "./dashboard/LineChart";



const lineChartData = {
  newVisitis: {
    liveData: [0, 0, 0, 0, 0, 0, 0],
    vodData: [0, 0, 0, 0, 0, 0, 0],
    vodDecryptData: [0, 0, 0, 0, 0, 0, 0],
    xData: [
      "-",
      "-",
      "-",
      "-",
      "-",
      "-",
      "-",
    ],
    liveText: "直播加密任务",
    vodText: "点播加密任务",
    vodDecryptText: "点播解密任务",
    certUseText : "证书使用量",
    surplusCertText : "证书剩余量",
    licenseText : "每日授权量",
  },
};

export default {
  name: "Index",
  dicts: ['sys_video_type',"sys_plot_type"],
  components: {
    PanelGroup,
    LineChart,
    CountTo,
  },
  data() {
    return {
      startUploadUrl: process.env.VUE_APP_BASE_API + "/api/startUpload", // 选中文件上传地址
      uploadProgressUrl: process.env.VUE_APP_BASE_API + "/api/uploadProgress/", // 文件上传进度请求地址
      // 版本号
      version: "3.8.9",
      timer: null, // 定时器变量
      numberRow: 2,
      treeData: [],
      treeProps: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf',
      },
      uploadProgress: -1,//上传进度
      uploadTaskId: null, // 用于存储后端返回的上传任务ID
      timer: null, // 用于存储定时器ID
      selectedFiles: [], // 用于存储选中目录下的文件
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openWarning: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 内容分类选项
      tvTypeOptions: [],
      // 内容分类的类型详情选项
      tvDataOptions: [],
      tvDataFlag:false,
      showTabFlag: 'task',
      showFlag: 'week',
      currentTab: 'week',
      radio: "week",
      lineChartData: lineChartData.newVisitis,
      upload: {
        url: process.env.VUE_APP_BASE_API + "/system/firstIndex/getLineInfo",
        urlStartWith:process.env.VUE_APP_BASE_API + "/system/firstIndex/getLineInfo",
      },
      channleCount1: 0,
      channleCount2: 0,
      contentCount: 0,
      contentDayCount: 0,
      certStorageValue: 0,
      certUseValue: 0,
      certIdleCount: 0,
      licenseCount: 0,
      uploadCount: {
        url: process.env.VUE_APP_BASE_API + "/system/firstIndex/getIndexInfo",
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {},
      // 上传完成提示框相关属性
      uploadSuccessTitle: "上传完成",
      uploadSuccessVisible: false,
    };
  },
  mounted() {
    // 在组件挂载后启动定时器
    this.timer = setInterval(() => {
        this.fetchData(); // 调用获取数据的方法
    }, 10000); // 每5秒执行一次5000==>10秒

  },
  created() {
    // this.getList();
    this.getEndValue();
    console.log("====created======="+this.showFlag);
  },
  methods: {

    handleTabClick() {
      console.log("====created======="+this.currentTab + "==========="+this.showTabFlag );
      this.upload.url = this.upload.urlStartWith + "?yTab="+this.showTabFlag+"&xTime="+this.currentTab;
      console.log("====this.upload.url======="+this.upload.url );
      this.getList();
    },
    getEndValue() {
      axios
        .get(this.uploadCount.url, {
          headers: { Authorization: "Bearer " + getToken() },
        })
        .then((response) => {
          // 使用箭头函数
          var data = response.data.data;
          // console.log("===任务数======="+JSON.stringify(response));
          this.channleCount1 = data.channleCount1;
          this.channleCount2 = data.channleCount2;
          this.contentCount = data.contentCount;
          this.contentDayCount = data.contentDayCount;
          // this.certStorageValue = data.certStorageCount;
          // this.certUseValue = data.certUseCount;
          // this.certIdleCount = data.certIdleCount;
          // this.licenseCount = data.licenseCount;
        })
        .catch(function (error) {
          // 处理错误
          console.error(error+"=======error====");
        });
    },
    changeLine(viewValue){
        console.log("=================首页点击======"+viewValue);
        this.showTabFlag = viewValue;
        // this.handleTabClick();
    },
    getList() {
      console.log("getList========"+this.upload.url);
      axios
        .get(this.upload.url, {
          headers: { Authorization: "Bearer " + getToken() },
        })
        .then((response) => {
          // 处理成功的响应
          var data = response.data.data;
          console.log("getList: "+JSON.stringify(data));
          this.lineChartData.xData = data.xdata;
          this.lineChartData.liveData = data.liveData;
          this.lineChartData.vodData = data.vodData;
          this.lineChartData.vodDecryptData = data.vodDecryptData;
          this.lineChartData.certUseData = data.certUseData;
          this.lineChartData.licenseData = data.licenseData;
          this.lineChartData.vodDecryptText = data.vodDecryptText;
          this.lineChartData.vodText = data.vodText;
          this.lineChartData.liveText = data.liveText;
          this.lineChartData.certUseText = data.certUseText;
          this.lineChartData.licenseText = data.licenseText;
        })
        .catch(function (error) {
          // 处理错误
          console.error(error);
        });
    },



    handleNodeClick(data, resolve ) {
      console.log("点击指定文件目录: "+data.path);
      // 点击节点时，获取当前节点的路径信息（这里假设data.path为节点路径）
      const path = data.path;
      getFileDataByPath(path).then(response => {
          console.log("获取指定文件: "+path+" 文件数据:"+JSON.stringify(response.data));
          this.selectedFiles = response.data;
        });
    },

    loadNode(node, resolve) {
      console.log("loadNode: "+node+"============"+node.level);
      //获取内容分类配置和剧情类型详情
      if (node.level === 0) {
        // 根节点请求后端获取数据
        getFileData().then(response => {
          resolve(response.data);
        });
      } else {
        console.log("模拟数据");
        const selectedNodeResultData = node.data;
        console.log("selectedNodeResultData: "+JSON.stringify(selectedNodeResultData));
        if (selectedNodeResultData &&!selectedNodeResultData.leaf) {
          const path = selectedNodeResultData.path;
          console.log("path: "+path);
          getFileDataByPath(path).then(response => {
            const children = response.data;
            resolve(children);
          });
        } else {
          resolve([]);
        }
      }
    },
    async fetchData() {
      try {
        console.log("发送定时任务检测系统是否有USB挂载");
        const response = await checkUsb(); // 调用API函数
        console.log('请求成功:', JSON.stringify(response));
        // 处理响应数据
        var data = response.data;
        console.log(JSON.stringify(data)+"======,弹框进行文件导入: "+this.openDataScope+" ,弹框提示: "+this.openWarning)
        if(data){
          //弹框展示
          if(!this.openWarning){
            this.openWarning = true;
            var row = this.numberRow;
            this.handleUpdate(row);
          }
        }else{
          //不存在或者已弹框
          this.no();
        }
      } catch (error) {
        console.error('发送定时任务,检测系统是否有挂载USB.请求失败:', error);
        // 处理错误
        this.no();
      }
    },
    beforeDestroy() {
      console.log("定时器被销毁");
    // 在组件销毁前清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  closeUploadSuccessDialog() {
      this.uploadSuccessVisible = false; // 隐藏上传完成提示框
  },
  no(){
    this.openWarning = false;
    this.openDataScope = false;
    this.beforeDestroy();
    console.log("销毁定时器");
  },
  yes(){
    this.openWarning = false;
    this.openDataScope = true;
    this.beforeDestroy();
  },
   // 表单重置
   reset() {
      this.form = {
        videoType: [],
        plotType: [],
      };
      this.resetForm("form");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = "导入USB文件";
    },
    submitData: function (){
      this.$refs["form"].validate(valid => {
        console.log("============提交校验:"+valid+"=======&&&&&&&&&&==="+JSON.stringify(this.form));
        if (valid) {
          const checkedNodes = this.$refs.tree.getCheckedNodes();
      console.log("提交信息 checkedNodes : "+JSON.stringify(checkedNodes));
      const filePaths = checkedNodes.map(node => node.path);
      console.log("提取需要上传的文件信息:"+JSON.stringify(filePaths)+"========"+filePaths.length);
      if(filePaths.length == 0){
        this.$modal.msgError("请选择上传的文件");
        return;
      }
      this.openDataScope = false;
      // this.$refs["form"].validate(valid => {
        const token = getToken();
        console.log("formData: "+JSON.stringify(filePaths)+"======="+this.form);
        var data = {
          filePaths:filePaths,
          // videoType:this.form.videoType,
          plotType:this.form.plotType,
        };
        console.log("提交数据: "+JSON.stringify(data));
        // axios.post('/dev-api/api/startUpload', data , {
        axios.post(this.startUploadUrl, data , {
          headers: {
            'Authorization': `Bearer `+token, // 假设 token 是你获取到的认证令牌
          },
        }).then(response => {
            var code = response.data.code;
            console.log("文件上传响应: "+JSON.stringify(response.data)+"==================code:"+code);
            if(code == 200){
              this.uploadTaskId = response.data.data;
              document.body.style.overflow = 'hidden'; // 禁用页面滚动
              this.timer = setInterval(() => {
                console.log("启动定时器");
                this.getUploadProgress();
              }, 1000);
            }else{
                this.$modal.msgError(JSON.stringify(response.data.msg));
                this.uploadProgress = -1;
            }
        }).catch(error => {
            console.error('上传失败', error);
            this.uploadProgress = -1;
        });
      // });


        }
      });

    },
    cancelData: function(){
      console.log("文件上传取消");
      this.openDataScope = false;
      this.reset();
    },
    getUploadProgress() {
      // console.log("getUploadProgress uploadTaskId: "+this.uploadTaskId);
      const token = getToken();
     // axios.get(`/dev-api/api/uploadProgress/${this.uploadTaskId}`,{
     axios.get(this.uploadProgressUrl+`${this.uploadTaskId}`,{
        headers: {
          'Authorization': `Bearer `+token, // 假设 token 是你获取到的认证令牌
        },
      })
        .then(response => {
          this.uploadProgress = response.data.progress;
          console.log("进度条: "+this.uploadProgress+"==========="+response.data.total);
          if (response.data.progress === 100) {
            clearInterval(this.timer);
            this.openDataScope = false;
            // this.$modal.msgSuccess("文件上传完成,请到内容管理模块查看上传的文件记录");
            document.body.style.overflow = 'auto'; // 恢复页面滚动
            this.uploadProgress = -1; // 重置上传进度，隐藏遮罩层
            this.uploadSuccessVisible = true; // 显示上传完成提示框
          }
        })
        .catch(error => {
          console.error('获取上传进度失败', error);
        });
      }
   },
  }
</script>


<style scoped>
/* 遮罩层样式 */
.upload-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999; /* 确保遮罩层在最上层 */
}

/* 进度条样式 */
.upload-overlay .el-progress {
  width: 50%; /* 进度条宽度 */
}
</style>

<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 30px;
  margin-top: -20px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 30px;
  }
}

@media (max-width: 1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>

<style lang="scss" scoped>

.default-scrollbar {
  width: 100%;
  height: 100%;
}
.flex-scrollbar {
  width: auto;
  height: auto;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
}
.panel-group {
  margin-top: 18px;

  .card-panel-col {
    margin-bottom: 20px;
    width: 25%;
    margin-left: -5px;
    // background-color: blur;
  }

  .card-panel {
    height: 108px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #fff;
    background: #fff;
    background-color: #17a0f0;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, 0.05);
    // border-color: rgba(0, 0, 0, 0.05);

    &:hover {
      .card-panel-icon-wrapper {
        color: #fff;
      }

      .icon-people {
        background: #40c9c6;
      }

      .icon-message {
        background: #36a3f7;
      }

      .icon-money {
        background: #f4516c;
      }

      .icon-shopping {
        background: #34bfa3;
      }
    }

    .icon-people {
      color: #40c9c6;
    }

    .icon-message {
      color: #36a3f7;
    }

    .icon-money {
      color: #f4516c;
    }

    .icon-shopping {
      color: #34bfa3;
    }

    .card-panel-icon-wrapper {
      float: left;
      margin: 14px 0 0 14px;
      padding: 16px;
      transition: all 0.38s ease-out;
      border-radius: 6px;
    }

    .card-panel-icon {
      float: left;
      font-size: 48px;
    }

    .card-panel-description {
      float: center;
      font-weight: bold;
      margin: 26px;
      margin-left: 60px;

      .card-panel-text {
        line-height: 18px;
        color: #fff;
        font-size: 14px;
        margin-bottom: 12px;
      }

      .card-panel-num {
        font-size: 20px;
      }
    }
  }
}

@media (max-width: 550px) {
  .card-panel-description {
    display: none;
  }

  .card-panel-icon-wrapper {
    float: none !important;
    width: 100%;
    height: 100%;
    margin: 0 !important;

    .svg-icon {
      display: block;
      margin: 14px auto !important;
      float: none !important;
    }
  }
}
</style>